<template>
  <view class="container">
    <view class="top">
      <!-- 搜索框 -->
      <view class="search-wrap">
        <uni-search-bar
          class="search"
          v-model="keyword"
          placeholder="请输入城市名"
          bgColor="#f5f5f5"
          clearButton="auto"
          cancelButton="none"
          @confirm="onSearchConfirm"
          @clear="onClear"
        />
      </view>

      <!-- 当前定位城市 -->
      <view class="block">
        <view class="block-title">当前定位城市</view>
        <view class="location-row">
          <view class="location-city" @click="handleLocation">
            <uni-icons type="location-filled" color="#333" size="22" />
            <text class="city">{{ locationCityDisplay }}</text>
          </view>
          <view class="relocate" @click="reLocate">
            <uni-icons type="loop" color="#4196e5" size="17" />
            <text class="text">重新定位</text>
          </view>
        </view>
      </view>
      <!-- 历史访问城市 -->
      <view class="block" v-if="historyList.length">
        <view class="block-title">历史访问城市</view>
        <view class="history-wrap">
          <view
            class="tag"
            v-for="item in historyList"
            :key="item"
            @click="chooseCity(item)"
            >{{ item }}</view
          >
          <!-- <view class="tag clear" @click="clearHistory">清空</view> -->
        </view>
      </view>
      <view class="block-title">省份/城市</view>
    </view>

    <!-- 省份/城市 索引列表 -->
    <view class="block city-list">
      <view class="indexed-wrap">
        <uni-indexed-list
          :options="filteredOptions"
          :showSelect="false"
          @click="onIndexedClick"
        />
      </view>
    </view>
    <view style="height: 20rpx"></view>
  </view>
</template>

<script setup lang="ts">
// 选择城市页面
// - 支持搜索过滤
// - 显示当前定位城市与历史访问城市
// - 使用 uni-indexed-list 展示按字母索引的城市列表

import { ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useCityStore } from "@/store/modules/city";
import { CITY_INDEXED_OPTIONS } from "@/utils/city-data";
// 关键字搜索
const keyword = ref("");
// 城市 Store
const cityStore = useCityStore();

// 历史城市与定位展示
const historyList = computed(() => cityStore.history);
const locationCityDisplay = computed(
  () => cityStore.locationCity || cityStore.currentCity || "未知"
);

// 原始索引数据
const allOptions = ref(CITY_INDEXED_OPTIONS);

// 过滤逻辑（中文包含判断）
const filteredOptions = computed(() => {
  const k = keyword.value.trim();
  if (!k) return allOptions.value;
  return allOptions.value
    .map((group) => ({
      letter: group.letter,
      data: group.data.filter((name) => name.includes(k)),
    }))
    .filter((group) => group.data.length > 0);
});

// 搜索栏事件
function onSearchConfirm(e: any) {
  // uni-search-bar v-model 已绑定，这里做兜底与键盘收起
  keyword.value = typeof e === "string" ? e : e?.value ?? keyword.value;
  uni.hideKeyboard();
}

function onClear() {
  keyword.value = "";
}

// 索引列表点击事件
function onIndexedClick(e: any) {
  // 组件回调结构：{ item: { name: '城市名', ... }, select: [] }
  const name = e?.item?.name;
  if (name) {
    chooseCity(name);
  }
}

// 选择城市的统一处理
function chooseCity(name: string) {
  cityStore.setCurrentCity(name);
  cityStore.addHistory(name);
  uni.showToast({ title: `已选择：${name}`, icon: "none", duration: 800 });
  setTimeout(() => {
    uni.navigateBack({ delta: 1 });
  }, 300);
}

// 清空历史
function clearHistory() {
  uni.showModal({
    title: "清空历史",
    content: "确定要清空历史访问城市吗？",
    success: (res) => {
      if (res.confirm) cityStore.clearHistory();
    },
  });
}

//
const handleLocation = () => {
  if (!locationCityDisplay) return;
  chooseCity(locationCityDisplay.value);
};

const getLocation = () => {
  uni.getLocation({
    type: "gcj02",
    // 部分平台支持 geocode 返回地址
    geocode: true as any,
    success: (res: any) => {
      // 不同平台字段差异较大，尽量兼容
      const city = res?.address?.city || res?.address?.district || "";
      if (city) {
        cityStore.setLocationCity(city);
        // cityStore.setCurrentCity(city);
        cityStore.addHistory(city);
        uni.showToast({ title: `定位到：${city}`, icon: "none" });
        return;
      }
      const latitude = res.latitude; // 纬度
      const longitude = res.longitude; // 经度
      const test = longitude + "," + latitude;
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=29ba51d04a274cf952b493b7d0b38ce5&location=${test}`;
      uni.request({
        url,
        success: (res) => {
          const city = (res as unknown as { data: GeocodeRes }).data?.regeocode
            .addressComponent.city;
          if (city) {
            cityStore.setLocationCity(city);
            uni.showToast({ title: `定位到：${city}`, icon: "none" });
          }
        },
        fail: () => {
          uni.showToast({ title: "定位失败，请稍后再试", icon: "none" });
        },
      });
    },
    fail: () => {
      uni.showToast({ title: "定位失败，请稍后再试", icon: "none" });
    },
    complete: () => {
      uni.hideLoading();
    },
  });
};

// 重新定位（尽量使用 geocode 获取城市名；失败则保留原值）
function reLocate() {
  uni.showLoading({ title: "定位中", mask: true });
  getLocation();
}

onMounted(() => {
  // 首次进入，如无定位城市，可尝试静默定位（可按需关闭）
  if (!cityStore.locationCity) {
    // 静默尝试一次，不弹窗
    uni.getLocation({
      type: "gcj02",
      geocode: true as any,
      success: (res: any) => {
        const city = res?.address?.city || "";
        if (city) {
          cityStore.setLocationCity(city);
        }
      },
    });
  }
});
</script>

<style lang="less" scoped>
.container {
  box-sizing: border-box;
  height: 100%;
  /* #ifdef APP-PLUS */
  height: 100%;
  /* #endif */
  /* #ifdef H5 */
  height: calc(100%-44px) !important;
  /* #endif */
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.uni-page-wrapper) {
  height: calc(100%-44px) !important;
  :deep(.uni-page-body){
    height: 100%;
  }
}
.search-wrap {
  margin-top: 15rpx;
  margin-bottom: 30rpx;
  width: 688rpx;
  height: 77rpx;
  //   background: #f5f5f5;
  border-radius: 69rpx;

  :deep(.uni-searchbar) {
    padding: 0 !important;
  }
  :deep(.uni-searchbar__box) {
    border-radius: 69rpx !important;
    padding: 0 !important;
  }
}

.block {
  margin-bottom: 31rpx;
  overflow: hidden;
}

.block-title {
  width: 162rpx;
  height: 38rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 27rpx;
  color: #aaaaaa;
  text-align: left;
  margin-bottom: 30rpx;
}

.location-row {
  display: flex;
  align-items: center;
  justify-self: start;
  gap: 15rpx;
}

.location-city {
  box-sizing: border-box;
  height: 58rpx;
  padding: 0 38rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  gap: 15rpx;

  .city {
    height: 38rpx;
    line-height: 40rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 27rpx;
    color: #333333;
    text-align: center;
  }
}

.relocate {
  //   width: 62rpx;
  height: 54rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .text {
    // width: 62rpx;
    height: 21rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 15rpx;
    color: #4196e5;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}

.history-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 11rpx;
}

.tag {
  box-sizing: border-box;
  width: 163rpx;
  height: 58rpx;
  line-height: 58rpx;
  text-align: center;
  background: #f5f5f5;
  border-radius: 12rpx;
  color: #aaa;
  font-size: 27rpx;
}

.tag.clear {
  background: #ffecec;
  color: #ff4d4f;
}

// 城市区域滚动
.top {
  flex-grow: 0;
  flex-shrink: 0;
}

.city-list {
  flex: 1;
}

.indexed-wrap {
  height: 100%;
  overflow: hidden;
  position: relative;
  background: #fff;
  border-radius: 16rpx;
  :deep(.uni-indexed-list__item-border) {
    border-bottom-color: #f1f1f1;
  }
  :deep(.uni-indexed-list__title-wrapper) {
    background-color: #b0d5e4;
    border-top-left-radius: 20rpx;
  }

  :deep(.uni-indexed-list__menu) {
    overflow: none;
  }
}
</style>
